package com.changyi.device.swipe;

import android.content.Context;

import com.landicorp.android.eptapi.DeviceService;
import com.landicorp.android.eptapi.device.MagCardReader;
import com.landicorp.android.eptapi.exception.ReloginException;
import com.landicorp.android.eptapi.exception.ReqeustException;
import com.landicorp.android.eptapi.exception.ServiceOccupiedException;
import com.landicorp.android.eptapi.exception.UnsupportMultiProcess;

public class A8Card implements ReadCardInterface{

    private Context mContext;
    private static A8Card a8Card;
    private ReadCardResultInterface readCardResultInterface;
    private A8Card(Context context) {
        mContext = context;
    }

    public static A8Card getInstance(Context context) {
        if (a8Card == null) {
            synchronized (A8Card.class){
                if (a8Card == null) {
                    a8Card = new A8Card(context);
                }
            }
        }
        return a8Card;
    }

    protected void startMagCardSearch() {
        try {
            MagCardReader.getInstance().searchCard(
                    new MagCardReader.OnSearchListener() {

                        @Override
                        public void onCardStriped(boolean[] hasTrack,String[] track) {
                            onMagCardStriped(hasTrack, track);
                        }

                        @Override
                        public boolean checkValid(int[] trackStates,
                                                  String[] track) {
                            for (int i = 0; i < trackStates.length; i++) {
                                if (trackStates[i] != TRACK_STATE_NULL) {
                                    break;
                                } else if (i == 2) {
                                    return false;
                                }
                            }
                            return super.checkValid(trackStates, track);
                        }

                        @Override
                        public void onFail(int code) {
                            String errorMsg = getErrorDescription(code);
                            if(readCardResultInterface!=null)
                                readCardResultInterface.cardResultSucsses(errorMsg);
                            startMagCardSearch();
                        }

                        public String getErrorDescription(int code) {
                            switch (code) {
                                case ERROR_INVALID:
                                    return "磁道数据不正确";
                                case ERROR_NEEDSTART:
                                    return "服务异常，需要重试";
                                case ERROR_NODATA:
                                    return "该卡无数据";
                            }
                            return "未知错误";
                        }

                        @Override
                        public void onCrash() {
                        }
                    });
        } catch (ReqeustException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void onMagCardStriped(boolean[] hasTrack, String[] track) {

        if (!hasTrack[1]) {
            return;
        }
        int sepIndex = track[1] == null ? -1 : track[1].indexOf('=');
        if (sepIndex > 0) {

            String serviceCode = getServiceCode(track[1]);
            if (null == serviceCode) {
                return;
            }
        }
        String msg = track[1].split("=")[0];
        if(readCardResultInterface!=null)
            readCardResultInterface.cardResultSucsses(msg);
    }

    private String getServiceCode(String track2) {
        int sepIndex = track2.indexOf('=');
        int serviceCodeIndex = sepIndex + 5;
        if (serviceCodeIndex + 3 > track2.length()) {
            return null;
        }
        return track2.substring(serviceCodeIndex, serviceCodeIndex + 3);
    }

    @Override
    public ReadCardInterface init() {
        try {
            DeviceService.login(mContext);
            MagCardReader.getInstance().setLRCCheckEnabled(true);
            MagCardReader.getInstance().enableTrack(
                    MagCardReader.TRK1 | MagCardReader.TRK2
                            | MagCardReader.TRK3);
            startMagCardSearch();
        } catch (ServiceOccupiedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (ReloginException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (UnsupportMultiProcess e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (ReqeustException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        return a8Card;
    }

    @Override
    public ReadCardInterface close() {
        DeviceService.logout();
        return a8Card;
    }

    @Override
    public ReadCardInterface setReadCardResult(ReadCardResultInterface readCardResultInterface) {
        this.readCardResultInterface = readCardResultInterface;
        return a8Card;
    }

}
